# -*- coding: UTF-8 -*-

import os

import importlib
import copy


def addons_load(root_path):

    def patch_xml_id(module_name, xml_name, one):
        xml_id = module_name + '.' + xml_name
        one2 = copy.deepcopy(one)
        one2.update({'xml_id': xml_id, 'id': xml_id})
        return one2

    def patch_module_name(module_name, str1):
        if not str1:
            return None
        else:
            length = len(str.split('.'))
            if length == 1:
                return module_name + '.' + str1
            else:
                return str1

    def load_menu(module_name, menu):
        return {}

    def load_view(one):
        one2 = copy.deepcopy(one)
        if not one.get('buttons'):
            one2['buttons'] = {}

        if not one.get('priority'):
            one2['priority'] = 16

        buttons = one2['buttons']
        if 'create' not in buttons:
            buttons['create'] = True
        if 'edit' not in buttons:
            buttons['edit'] = True
        if 'delete' not in buttons:
            buttons['delete'] = True

        return one2

    def load_action(module_name, one):
        one2 = copy.deepcopy(one)
        if not one.get('views'):
            one['views'] = {}

        search_view_id = one.get('search_view_id')
        search_view_id = patch_module_name(module_name, search_view_id)
        if search_view_id:
            one2['search_view_id'] = search_view_id

        view_mode = one.get('view_mode', ['tree', 'kanban', 'form'])

        if not one.get('views'):
            one2['views'] = {}

        views = one2['views']

        for mode in view_mode:
            view = patch_module_name(module_name, views.get(mode))
            if view:
                views[mode] = view

        return one2

    def load_one_addons(records1, module_name):
        if not records1:
            return {}

        result = {}
        for name, val in records1.items():
            one = patch_xml_id(module_name, name, val)
            # print('load_one_addons', one)

            if one['_odoo_model'] == 'ir.ui.menu':
                menus = load_menu(module_name, one)
                result.update(menus)
            elif one['_odoo_model'] == 'ir.actions':
                one2 = load_action(module_name, one)
                result[one2['xml_id']] = one2
            elif one['_odoo_model'] == 'ir.ui.view':
                one2 = load_view(one)
                result[one2['xml_id']] = one2
            else:
                result[one['xml_id']] = one

        return result

    all_records = {}
    all_modules = []
    for home, dirs, files in os.walk(root_path):
        # print(home, dirs, files)
        if home == root_path:
            all_modules = [dir for dir in dirs if dir[0] != '_']
            # print('all_modules', all_modules)
            continue

        module_name = home[len(root_path)+1:]
        if module_name in all_modules:
            for file in files:
                file_name = file.split('.')[0]
                module_path = home + '/' + file_name
                module_path = '.'.join(module_path.split('/'))
                # print(module_path, file_name)
                record_module = importlib.import_module(module_path)
                record = record_module.record
                # print(module_path, record)
                one_addons = load_one_addons(record, module_name)
                all_records.update(one_addons)

    # for key, val in all_records.items():
    #     print(key)

    return all_records


class Addons(object):
    def __init__(self, addons_list):
        self.addons_list = addons_list or []

    @property
    def data(self):
        return self.load(self.addons_list)

    def load(self, addons_list):
        res = {}
        for addons in addons_list:
            one = addons_load(addons)
            res.update(one)

        def filter_fn(res, odoo_model):
            return dict((k, v) for k, v in res.items() if v['_odoo_model'] == odoo_model)

        actions = filter_fn(res, 'ir.actions')
        views = filter_fn(res, 'ir.ui.view')
        menus = {}
        return {'menus': menus, 'actions': actions, 'views': views}


class Action(object):
    def __str__(self):
        return 'Action(' + self.xml_id + ')'

    def __init__(self, action_id, env=None, context=None, from_odoo=None):
        self.env = env
        self.xml_id = action_id

        if from_odoo:
            ref = env.ref(action_id)
            info = env.rpc.web.action.load(ref.res_id)
        else:
            if isinstance(action_id, str):
                info = self.actions_load(action_id)
            else:
                info = action_id

        self.info = info

    @property
    def context(self):
        # const ctx1 = this.context_default
        # const ctx2 = this.env.context
        # return { ...ctx2, ...ctx1 }
        return {}

    def actions_load(self, action):
        addons_data = self.env.rpc.addons.data
        actions = addons_data['actions']
        info = actions[action]
        info2 = copy.deepcopy(info)

        views_all = addons_data['views']

        views = {}
        for view_type, view_name in info['views'].items():
            view_info = views_all.get(view_name, {})
            views[view_type] = view_info

        info2['views'] = views

        return info2
